package com.example.lin.utils;

import org.springframework.stereotype.Component;

import java.security.SecureRandom;

/**
 * @author Administrator
 */
@Component
public class VerifyCodeUtil {

    private static final SecureRandom RANDOM = new SecureRandom();

    private static final String CHARACTERS = "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz";

    private static final int DEFAULT_LENGTH = 6;

    private VerifyCodeUtil() {}

    /**
     * 生成指定长度的校验码
     *
     * @param length 校验码长度
     * @return 生成的校验码
     */
    public static String generateVerifyCode(int length) {
        if (length <= 0) {
            throw new IllegalArgumentException("长度必须大于0！");
        }
        StringBuilder code = new StringBuilder(length);
        for (int i = 0; i < length; i++) {
            int index = RANDOM.nextInt(CHARACTERS.length());
            code.append(CHARACTERS.charAt(index));
        }
        return code.toString();
    }

    /**
     * 生成默认长度的校验码
     *
     * @return 生成的校验码
     */
    public static String generateVerifyCode() {
        return generateVerifyCode(DEFAULT_LENGTH);
    }

    /**
     * 验证校验码
     *
     * @param verifyCode 输入的校验码
     * @param expected 预期的校验码
     * @return 如果输入的校验码与预期的校验码匹配，则返回 true，否则返回 false
     */
    public static boolean validVerifyCode(String verifyCode, String expected) {
        if (verifyCode == null || expected == null) {
            return false;
        }
        return verifyCode.equals(expected);
    }
}
